package dao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Session;

import beans.Customer;
import util.HibernateManager;

/**
 * 通用数据库操作类
 * 
 * @author 崔诗新
 *
 * @param <T>
 *            要操作的类型
 */
@SuppressWarnings("unchecked")
public class DAO<T> {
	Session session = null;
	Class<T> type = null;

	public DAO(Class<T> type) {
		session = HibernateManager.getSession();
		this.type = type;
	}

	/**
	 * 根据hql语句更新信息
	 * 
	 * @param hql
	 */
	public void update(String hql) {
		session.getTransaction().begin();
		session.createQuery(hql).executeUpdate();
		session.getTransaction().commit();
	}

	/**
	 * 根据hql语句更新信息
	 * 
	 * @param hql
	 */
	public void updateSQL(String sql) {
		session.getTransaction().begin();
		session.createSQLQuery(sql).executeUpdate();
		session.getTransaction().commit();
	}

	/**
	 * 添加任务信息
	 * 
	 * @param info
	 */
	public void add(T info) {
		session.getTransaction().begin();
		session.save(info);
		session.getTransaction().commit();
	}

	/**
	 * 分页查询所有信息
	 * 
	 * @param startP
	 *            从第几条开始
	 * @param number
	 *            查询多少条数据
	 * @return
	 */
	public Map<Long, List<T>> getAll(int startP, int number) {
		List<T> tasks = new ArrayList<>();
		String hql = "from " + type.getSimpleName() + " order by id desc";
		tasks = session.createQuery(hql).setFirstResult(startP).setMaxResults(number).list();
		hql = "select count(*) " + hql;
		Long count = (Long) session.createQuery(hql).list().get(0);
		Map<Long, List<T>> map = new HashMap<>();
		map.put(count, tasks);
		return map;
	}

	/**
	 * 根据hql分页查询信息
	 * 
	 * @param startP
	 *            从第几条开始
	 * @param number
	 *            查询多少条数据
	 * @return Map <数据条数，查询结果列表>
	 */
	public Map<Long, List<T>> getFromHQL(String hql, int startP, int number) {
		List<T> tasks = new ArrayList<>();
		tasks = session.createQuery(hql).setFirstResult(startP).setMaxResults(number).list();
		if (hql.contains("*"))
			hql = hql.replace("*", "count(*)");
		else 
			hql = "select count(*) " + hql;
		Long count = (Long) session.createQuery(hql).list().get(0);
		Map<Long, List<T>> map = new HashMap<>();
		map.put(count, tasks);
		return map;
	}

	/**
	 * 根据id查询信息
	 * 
	 * @param id
	 * @return
	 */
	public T getById(int id) {
		T task = (T) session.get(type, id);
		return task;
	}

	/**
	 * 根据id删除信息
	 * 
	 * @param id
	 * @return
	 */
	public void delById(int id) {
		String hql = "delete from " + type.getSimpleName() + " where id=" + id;
		session.getTransaction().begin();
		session.createQuery(hql).executeUpdate();
		session.getTransaction().commit();
	}
	
	public Session getSession() {
		return session;
	}
}
